import React, { useState, useEffect, Suspense } from 'react';
import { Outlet, Link, useNavigate, useLocation } from 'react-router-dom';
import { Layout, Menu, Button, Dropdown, Avatar, Badge, Space, theme } from 'antd';
import {
  HomeOutlined,
  BookOutlined,
  TrophyOutlined,
  UserOutlined,
  LogoutOutlined,
  DashboardOutlined,
  BellOutlined,
  LoginOutlined,
  UserAddOutlined,
  FileTextOutlined,
  CodeOutlined,
} from '@ant-design/icons';
import type { MenuProps } from 'antd';
import Footer from './Footer';
import './UserLayout.css';
import { useAuthStore } from '@/store/useAuthStore';
import LoadingSpinner from '@/components/LoadingSpinner';
import { useWebsiteStore } from '@/store/useWebsiteStore';
import DocumentTitle from '@/components/DocumentTitle';
import BreadcrumbNav from '@/components/Breadcrumb';
import http from '@/http';
import { accountService } from '@/services/accountService';

const { Header, Content } = Layout;

const UserLayout: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { isAuthenticated, user, clearAuth, isAdmin } = useAuthStore();
  const [selectedKeys, setSelectedKeys] = useState<string[]>(['home']);
  const [avatarUrl, setAvatarUrl] = useState<string | undefined>(undefined);
  const { token } = theme.useToken();
  
  // 直接使用配置
  const { config } = useWebsiteStore();
  const websiteName = config?.website_name || 'Online Judge';
  
  useEffect(() => {
    // 根据当前路径设置选中的菜单项
    const path = location.pathname.split('/')[1] || 'home';
    setSelectedKeys([path]);
  }, [location.pathname]);

  // 检查用户 profile 并获取头像
  useEffect(() => {
    if (isAuthenticated && user) {
      const checkProfileAndFetchAvatar = async () => {
        try {
          const response = await accountService.getProfile();
          const profileData = response.data;
          
          // 检查用户是否有 profile
          if (profileData && profileData.has_profile === false) {
            // 如果没有 profile，且不在完善资料页面，则跳转到完善资料页面
            if (location.pathname !== '/profile/complete') {
              navigate('/profile/complete', { 
                replace: true,
                state: { message: '请先完善您的个人资料' }
              });
            }
          } else if (profileData && profileData.avatar) {
            // 有 profile，设置头像
            setAvatarUrl(profileData.avatar);
          }
        } catch (error) {
          console.error('获取用户资料失败:', error);
        }
      };
      
      checkProfileAndFetchAvatar();
    }
  }, [isAuthenticated, user, location.pathname, navigate]);

  // 处理登出
  const handleLogout = () => {
    clearAuth();
    setAvatarUrl(undefined);
    navigate('/login');
  };

  // 跳转到管理员面板
  const goToAdmin = () => {
    navigate('/admin/');
  };

  const userMenuItems: MenuProps['items'] = [
    {
      key: 'profile',
      label: '个人资料',
      icon: <UserOutlined />,
      onClick: () => navigate('/profile'),
    },
    isAdmin ? {
      key: 'admin',
      label: '管理员面板',
      icon: <DashboardOutlined />,
      onClick: goToAdmin,
    } : null,
    {
      type: 'divider',
    },
    {
      key: 'logout',
      label: '退出登录',
      icon: <LogoutOutlined />,
      onClick: handleLogout,
    },
  ].filter(Boolean) as MenuProps['items'];

  // 使用这种格式来确保Link和图标颜色一致
  const renderMenuLabel = (path: string, label: string, icon: React.ReactNode) => (
    <Link to={path} className="menu-link">
      {icon} <span>{label}</span>
    </Link>
  );

  const navItems: MenuProps['items'] = [
    {
      key: 'home',
      label: renderMenuLabel('/', '首页', <HomeOutlined />),
    },
    {
      key: 'problem',
      label: renderMenuLabel('/problem/list', '题目', <BookOutlined />),
    },
    {
      key: 'practice',
      label: renderMenuLabel('/practice', '练习', <CodeOutlined />),
    },
    {
      key: 'contest',
      label: renderMenuLabel('/contest/list', '比赛', <TrophyOutlined />),
    },
    // {
    //   key: 'discussion',
    //   label: renderMenuLabel('/discussion', '讨论', <CommentOutlined />),
    // },
    // {
    //   key: 'learn',
    //   label: renderMenuLabel('/learn', '学习', <ReadOutlined />),
    // },
    // {
    //   key: 'question',
    //   label: renderMenuLabel('/question/list', '问答', <QuestionCircleOutlined />),
    // },
    {
      key: 'paper',
      label: renderMenuLabel('/client/paper/list', '试卷', <FileTextOutlined />),
    },
  ];

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <DocumentTitle />
      <Header className="header light-header">
        <div className="logo">{websiteName}</div>
        <Menu
          theme="light"
          mode="horizontal"
          selectedKeys={selectedKeys}
          items={navItems}
          className="nav-menu"
        />
        <div className="header-right">
          {isAuthenticated && user ? (
            <Space size="middle">
              <Badge count={user.notifications || 0} size="small">
                <Button
                  icon={<BellOutlined />}
                  type="text"
                  shape="circle"
                  onClick={() => navigate('/notifications')}
                />
              </Badge>
              <Dropdown menu={{ items: userMenuItems }} placement="bottomRight">
                <Space className="user-dropdown">
                  <Avatar 
                    size="default" 
                    icon={<UserOutlined />} 
                    src={avatarUrl ? http.getAvatarUrl(avatarUrl) : undefined}
                    style={{ backgroundColor: token.colorPrimary }}
                  />
                  <span className="username-light">{user.username}</span>
                </Space>
              </Dropdown>
            </Space>
          ) : (
            <Space size="large">
              <Button 
                type="primary" 
                icon={<LoginOutlined />}
                onClick={() => navigate('/login')}
                className="login-btn"
              >
                登录
              </Button>
              <Button 
                type="primary" 
                icon={<UserAddOutlined />}
                onClick={() => navigate('/register')}
                className="register-btn"
              >
                注册
              </Button>
            </Space>
          )}
        </div>
      </Header>
      <div className="breadcrumb-container">
        <BreadcrumbNav />
      </div>
      <Content className="content">
        <div className="content-container">
          <Suspense fallback={<LoadingSpinner tip="加载用户功能..." />}>
            <Outlet />
          </Suspense>
        </div>
      </Content>
      <Footer />
    </Layout>
  );
};

export default UserLayout; 